package com.sndscl.rpc.netty;

import com.sndscl.rpc.common.constant.SndSclConstant;
import com.sndscl.rpc.common.rpc.RequestDecoder;
import com.sndscl.rpc.common.rpc.ResponseEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @Description
 * @Author lsh
 * @Date 2020/10/13 17:20
 **/
public class SndsclNettyServer {

    public void startService(int port){
        NioEventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .localAddress(port)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast("delimiter", new DelimiterBasedFrameDecoder(3145728,true,
                                        Unpooled.copiedBuffer(SndSclConstant.NETTY_DELIMITER.getBytes())))
                                .addLast(new IdleStateHandler(10,0,0))
                                .addLast(new RequestDecoder())
                                .addLast(new ResponseEncoder())
                                .addLast(new RequestHandler());
                    }
                });
        try {
            ChannelFuture future = serverBootstrap.bind().sync(); //绑定服务，等待服务关闭
            System.out.println(SndsclNettyServer.class.getName() + " started and listen on " + future.channel().localAddress());
            future.channel().closeFuture().sync();//关闭 channel 和 块，直到它被关闭
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            try {
                group.shutdownGracefully().sync();//关机的 EventLoopGroup，释放所有资源。
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
